package pri.zey.custom.tools;/**
 * Created by Administrator on 2016/3/16.
 */

import android.util.Log;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * 编码工具
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 */
public class TenCode {

    private final String TAG = "TenCode";

    /**
     * @param timestemp 时间戳
     * @param nonce 流水号
     * @param token
     * SHA1加密
     */
    public String endecodeSHA1(String token, String nonce, String timestemp){
        String tempStr = token + timestemp + nonce;
        tempStr = encodePassword(tempStr, "sha-1");
        return tempStr;
    }

    /**
     * 随机生成8位密码
     *
     * @param length
     * @return
     */
    public String generatePassword(int length) {
        java.util.Random r = new java.util.Random();
        StringBuilder sb = new StringBuilder();
        if (length <= 0) {
            length = 6;
        }
        for (int i = 0; i < length; i++) {
            sb.append(Integer.toString(r.nextInt(36), 36));
        }
        return sb.toString();
    }

    public String getRandom(int length) {

        return "";
    }

    /**
     * 用指定的加密算法加密【普通】
     *
     * @param password  Password or other credentials to use in authenticating this username
     * @param algorithm Algorithm used to do the digest
     * @return encypted password based on the algorithm.
     */
    public String encodePassword(String password, String algorithm) {
        String encypted = "";
        MessageDigest md;
        byte[] unencodedPassword = password.getBytes();
        try {
            // first create an instance, given the provider
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            Log.i(TAG, "Exception: " + e);
            return password;
        }
        md.reset();
        // call the update method one or more times
        // (useful when you don't know the size of your data, eg. stream)
        md.update(unencodedPassword);

        // now calculate the hash
        byte[] encodedPassword = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }

            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }
        encypted = buf.toString().toLowerCase();
        return encypted;
    }


    /**
     * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     * 加密：AES/ECB/PKCS7Padding
     */
    /*
     * 引用资源包：bcprov-jdk15on-154     +   commons-codec-1.9
     * 此处使用AES-128-ECB加密模式，key需要为16位。
     */
    private final byte[] key = new byte[]{ 0x50, 0x47, 0x21, 0x76, 0x30, 0x28, 0x27, 0x37, 0x58, 0x75,
            0x40, 0x40, 0x34, 0x64, 0x32, 0x33 };
    private final String algorithm = "AES";
    private final String transformation = "AES/ECB/PKCS7Padding";
    private final String provider = "BC";
    private byte[] EDinit(byte[] input, int opmode){
        Security.addProvider(new BouncyCastleProvider());//因为使用的是PKCS7所以需要引用bcprov中的次方法解除jdk解码长度限制
        byte[] result = null;
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
            Cipher cipher = Cipher.getInstance(transformation, provider);
            cipher.init(opmode, keySpec);
            result = cipher.doFinal(input);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    // 加密
    private String AESEncrypt(String input){
        byte[] encrypted = EDinit(input.getBytes(), Cipher.ENCRYPT_MODE);
        String result = new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用
        return result;
    }

    // 解密
    public String AESDecrypt(String input){
        byte[] original = EDinit(new Base64().decode(input), Cipher.DECRYPT_MODE);
        String result = null;
        try {
            result = new String(original,"utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 加密：AES/ECB/PKCS7Padding
     * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     */
}
